package com.gift.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.gift.common.JsonMapper;
import com.gift.common.MD5Utility;
import com.gift.common.RequestHolder;
import com.gift.pojo.Games;
import com.gift.pojo.UserTable;

import com.gift.service.GamesService;
import com.gift.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/home")
public class HomeController {


    @Resource
    UserService userService;
    @Resource
    GamesService gamesService;


    //登录页面
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login() {
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            return "redirect:index";
        }
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (req.getSession().getAttribute("loginerror") == null) {
            req.getSession().setAttribute("loginerror", "请输入账号和密码!");
        }
        return "login";
    }

    // 登录
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(@Param("loginName") String loginName
            , @Param("passWord") String passWord
            , @Param("verCode") String verCode, HttpServletRequest request) {
        RequestHolder.add(request);
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String strCode = (String) req.getSession().getAttribute("strCode");
        String page = "login";
        if (verCode.equals(strCode)) {
            String MD5passWord = MD5Utility.encrypt(passWord);
            page = userService.login(loginName, MD5passWord);
        } else {
            req.getSession().setAttribute("loginerror", "验证码错误!");
        }
        return "redirect:" + page;
    }



    //注册页面
    @RequestMapping("/registinfo")
    public String registinfo() {

        return "registinfo";
    }


//开始注册
    @RequestMapping("/goRegistinfo")
    public String unauthorized(@Param("insetlist") String insetlist,HttpServletRequest request) {
        RequestHolder.add(request);
        String page = "login";

        UserTable user = JsonMapper.string2Obj(insetlist, new TypeReference<UserTable>() {
        });
        page = userService.newOne(user);

        return  "redirect:" + page;

    }



    // 系统首页
    @RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView mv=new ModelAndView();
        mv.setViewName("index");
        Subject currentUser = SecurityUtils.getSubject();
        UserTable user = (UserTable)currentUser.getPrincipal();
        mv.addObject("userName",user.getRelname());
        mv.addObject("menu", getChildSiteMap());
        SecurityUtils.getSubject().getSession().setTimeout(7200000);
        return mv;
    }



    //加载游戏菜单
    private String getChildSiteMap() {
        StringBuilder stringBuilder = new StringBuilder();
        List<Games> listNode = gamesService.getAll();


            if (listNode != null && !listNode.isEmpty()) {
                stringBuilder.append("<ul class=\"easyui-tree side-tree\">");
                for (Games item : listNode) {

                    stringBuilder.append("<li iconCls=\".icon-edit\"><a href=\"javascript:;\" title=\"" + item.getGname() + "\" data-icon=\"icon-chart-organisation\" data-link=\"/dealTable/sellBusiness?Gid=" + item.getGid() + "\" iframe=\"1\">" + item.getGname() + "</a>");

                    stringBuilder.append("</li>");
                }
                stringBuilder.append("</ul>");
            }

        return stringBuilder.toString();
    }




    // 退出系统
    @RequestMapping("/logOut")
    public String logOut() {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return "login";
    }

    //无角色或未授权跳转页面
    @RequestMapping("/ery")
    public String unauthorized() {

        return "error/unauthorizedUrl";
    }

    // 校验验证码
    @RequestMapping(value = "/strCode", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> strCode(String verCode) {
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String strCode = (String) req.getSession().getAttribute("strCode");

        Map<String, String> map = new HashMap<>();
        if (verCode.equals(strCode)) {
            map.put("ok", "");
        } else {
            map.put("error", "验证码错误");
        }
        return map;
    }

    // 生成验证码
    @RequestMapping("authCode")
    public void getAuthCode(HttpServletResponse response)
            throws IOException {
        int WIDTH = 80;
        int HEIGHT = 34;
        Random random = new Random();
        //设置response头信息
        //禁止缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        //生成缓冲区image类
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, 1);
        //产生image类的Graphics用于绘制操作
        Graphics g = image.getGraphics();
        //Graphics类的样式
        g.setColor(getRandColor(200, 250));
        g.setFont(getRandFont());
        g.fillRect(0, 0, WIDTH, HEIGHT);
        //绘制干扰线
        for (int i = 0; i < 80; i++) {
            g.setColor(getRandColor(130, 200));
            int x = random.nextInt(WIDTH);
            int y = random.nextInt(HEIGHT);
            int x1 = random.nextInt(12);
            int y1 = random.nextInt(12);
            g.drawLine(x, y, x + x1, y + y1);
        }

        //绘制字符
        String strCode = UUID.randomUUID().toString().substring(0, 4);
        for (int i = 0; i < strCode.length(); i++) {
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(strCode.substring(i, i + 1), 16 * i + 6, 28);
        }

        //将字符保存到session中用于前端的验证
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        req.getSession().setAttribute("strCode", strCode);
        g.dispose();

        ImageIO.write(image, "JPEG", response.getOutputStream());
        response.getOutputStream().flush();
    }

    // 创建颜色
    private Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    // 随机获取一个字体
    private Font getRandFont() {
        String[] fonts = new String[]
                {
                        "Arial",
                        "Helvetica",
                        "Geneva",
                        "sans-serif",
                        "Verdana",
                        "Tahoma",
                        "Gadugi",
                        "Terminal",
                        "Bell",
                        "VINERITC"
                };
        Random random = new Random();
        return new Font(fonts[random.nextInt(fonts.length)], 0, 28);
    }
}